package com.etrans.util;
import java.io.*;
import java.net.*;
import java.security.*;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.etrans.service.mobile.SMSService;

public class SMSUtil {
	/*
	 * webservice服务器定义
	 */
	 // 我们所有的Demo，都是在GBK环境下测试的。
	 //调用注册方法可能不成功。
	 //java.io.IOException: Server returned HTTP response code: 400 for URL: http://sdk105.entinfo.cn/webservice.asmx。
	 //如果出现上述400错误，请参考第102行。
	 //如果您的系统是utf-8，收到的短信可能是乱码，请参考第290行
	private final static String serviceURL = "http://sdk105.entinfo.cn/webservice.asmx";
	private final static String FUTIAN_SERVICE_URL = "http://172.24.2.208:809/service1.asmx";

	private static String sn = "SDK-SZW-010-00009";// 序列号
	private static String password = "f@a367@4";
	private static String pwd = "";// 密码
	
	public final static String DRIVER_MSG_MODULE_ID = "DRIVER_APP"; 
	public final static String COMPREHENSIVE_APP = "COMPREHENSIVE_APP";
	
	
	private static String prefix = "【福田汽车】";

	static {
		try{
			pwd = getMD5(sn + password);
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	/*
	 * 方法名称：mt 
	 * 功    能：发送短信 ,传多个手机号就是群发，一个手机号就是单条提交
	 * 参    数：mobile,content,ext,stime,rrid(手机号，内容，扩展码，定时时间，唯一标识)
	 * 返 回 值：唯一标识，如果不填写rrid将返回系统生成的
	 */
	public static String mt(String mobile, String content, String ext, String stime,
			String rrid) {
		
		System.out.print("==================================================================");
		System.out.println(String.format("sn=%s,password=%s,pwd=%s",sn,password,pwd));
		
		String result = "";
		String soapAction = "http://tempuri.org/mt";
		String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
		xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
		xml += "<soap:Body>";
		xml += "<mt xmlns=\"http://tempuri.org/\">";
		xml += "<sn>" + sn + "</sn>";
		xml += "<pwd>" + pwd + "</pwd>";
		xml += "<mobile>" + mobile + "</mobile>";
		xml += "<content>" +  prefix +content + "</content>";
		xml += "<ext>" + ext + "</ext>";
		xml += "<stime>" + stime + "</stime>";
		xml += "<rrid>" + rrid + "</rrid>";
		xml += "</mt>";
		xml += "</soap:Body>";
		xml += "</soap:Envelope>";
		System.out.println("xml = " + xml);
		URL url;
		try {
			url = new URL(serviceURL);

			URLConnection connection = url.openConnection();
			HttpURLConnection httpconn = (HttpURLConnection) connection;
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			//bout.write(xml.getBytes());
			//如果您的系统是utf-8,这里请改成
			bout.write(xml.getBytes("GBK"));

			byte[] b = bout.toByteArray();
			httpconn.setRequestProperty("Content-Length", String
					.valueOf(b.length));
			httpconn.setRequestProperty("Content-Type",
					"text/xml; charset=gb2312");
			httpconn.setRequestProperty("SOAPAction", soapAction);
			httpconn.setRequestMethod("POST");
			httpconn.setDoInput(true);
			httpconn.setDoOutput(true);

			OutputStream out = httpconn.getOutputStream();
			out.write(b);
			out.close();

			InputStreamReader isr = new InputStreamReader(httpconn
					.getInputStream());
			BufferedReader in = new BufferedReader(isr);
			String inputLine;
			while (null != (inputLine = in.readLine())) {
				Pattern pattern = Pattern.compile("<mtResult>(.*)</mtResult>");
				Matcher matcher = pattern.matcher(inputLine);
				while (matcher.find()) {
					result = matcher.group(1);
				}
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return "100";
		}
	}

	
	public static String sendPhoneMessage(String mobile, String message) {
		String result = "";
		String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
					+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
						  + "<soap:Body>"
						  + "<SendSms3 xmlns=\"http://tempuri.org/\">"
						       + "<login_name>loyalty</login_name>"
						       + "<password>123456</password>"
						       + "<mobile>" + mobile + "</mobile>"
						       + "<message>" + message + "</message>"
						     + "</SendSms3>"
						   + "</soap:Body>"
						 + "</soap:Envelope>";
		URL url;
		try {
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			bout.write(xml.getBytes("UTF-8"));
			byte[] b = bout.toByteArray();
			
			url = new URL(FUTIAN_SERVICE_URL);
			URLConnection connection = url.openConnection();
			HttpURLConnection httpconn = (HttpURLConnection) connection;
			httpconn.setRequestProperty("Content-Type",
					"text/xml; charset=utf-8");
			httpconn.setRequestProperty("Content-Length", String
					.valueOf(b.length));
			httpconn.setRequestProperty("SOAPAction", "http://tempuri.org/SendSms3");
			httpconn.setRequestMethod("POST");
			httpconn.setDoInput(true);
			httpconn.setDoOutput(true);

			OutputStream out = httpconn.getOutputStream();
			out.write(b);
			out.close();

			InputStreamReader isr = new InputStreamReader(httpconn
					.getInputStream());
			BufferedReader in = new BufferedReader(isr);
			String inputLine;
			Pattern pattern = Pattern.compile("<SendSms3Result>(.*)</SendSms3Result>");
			while (null != (inputLine = in.readLine())) {
				Matcher matcher = pattern.matcher(inputLine);
				while (matcher.find()) {
					result = matcher.group(1);
					break;
				}
			}
			
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return "100";
		}
	}
	
	/*
	 * 方法名称：getMD5 
	 * 功    能：字符串MD5加密 
	 * 参    数：待转换字符串 
	 * 返 回 值：加密之后字符串
	 */
	private static String getMD5(String sourceStr) throws UnsupportedEncodingException {
		String resultStr = "";
		try {
			byte[] temp = sourceStr.getBytes();
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(temp);
			// resultStr = new String(md5.digest());
			byte[] b = md5.digest();
			for (int i = 0; i < b.length; i++) {
				char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
						'9', 'A', 'B', 'C', 'D', 'E', 'F' };
				char[] ob = new char[2];
				ob[0] = digit[(b[i] >>> 4) & 0X0F];
				ob[1] = digit[b[i] & 0X0F];
				resultStr += new String(ob);
			}
			return resultStr;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}

	
	public static void main(String[] args){
		System.out.println(String.format("sn=%s,password=%s,pwd=%s",sn,password,pwd));
	}
	
	/** 
	 * 短信入库
	 */
	public static void saveMessage(Map<String,Object> param){
		SMSService smsService = (SMSService)SpringWebContextUtil.getApplicationContext().getBean("SMSService");
		smsService.saveMessage(param);
	}
}



